package com.pine.dcts.utils;


import com.pine.dcts.common.DatasourceType;
import com.pine.dcts.common.DctsException;
import com.pine.dcts.entity.DatasourceInfo;
import lombok.extern.slf4j.Slf4j;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


/**
 * @author xyjxust
 * @create 2019/6/25 15:28
 **/
@Slf4j
public class JdbcUtils {


//    public static SqlRunner getSqlRunner(String type, String username, String password, String ip, Integer port, String sid ){
//        Connection conn = buildConnection(type, username, password, ip, port, sid);
//        return new SqlRunner(conn);
//    }
//
//    public static Connection buildConnection(String type, String username, String password, String ip, Integer port, String sid){
//        Connection conn = null;
//
//        try {
//            DatasourceType dbType =   DatasourceType.valueOf(type.toUpperCase());
//            if(dbType==null){
//                throw new DctsException("未找到数据库类型["+type+"],请先在DatasourceType中进行注册");
//            }
//            Class.forName(dbType.getDriverClassName());
//            String url= String.format(dbType.getUrl(),ip,port,sid);
//            conn=  DriverManager.getConnection(url,username,password);
//
//        } catch (SQLException e) {
//            throw new DctsException("数据连接异常",e);
//        } catch (ClassNotFoundException e) {
//            throw new DctsException(String.format("未找到[%s]加载器，加载驱动程序失败！",type),e);
//        }catch(Exception e) {
//            throw new DctsException("数据连接异常：未知错误",e);
//        }
//        return conn;
//    }


    public static Connection buildConnection(DatasourceInfo datasourceInfo) {
        Connection conn = null;
        DatasourceType dbType = null;
        try {
            dbType = datasourceInfo.getType();
            if (dbType == null) {
                throw new DctsException("数据库类型为空");
            }
            Class.forName(dbType.getDriverClassName());
            conn = DriverManager.getConnection(datasourceInfo.getJdbcUrl(), datasourceInfo.getUsername(), datasourceInfo.getPassword());

        } catch (SQLException e) {
            throw new DctsException("数据连接异常", e);
        } catch (ClassNotFoundException e) {
            throw new DctsException(String.format("未找到[%s]加载器，加载驱动程序失败！", dbType.getDriverClassName()), e);
        } catch (Exception e) {
            throw new DctsException("数据连接异常：未知错误", e);
        }
        return conn;
    }


    public static void close(AutoCloseable conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            log.error("关闭jdbc连接错误", e);
        }
    }
}
